amJumping = false;

function months2i(monthString){
    monthString = monthString.toUpperCase();
    for (var i=0; i<12; i++)
    {
        if (monthString == monthsArray[i]) {
            monthString = i;
        }
    }
    return monthString;
}


var monthsArray = ['','JAN','FEB','MAR','APR','MAY','JUN','JUL',
                    'AUG','SEP','OCT','NOV','DEC'];


function getSiteCfg() { 
    $.getJSON(
        "/api/ocie/config_public/",
        function(json){
            var val = 'POC: <a class="POCemail" href="mailto:' +
                      json.ocie_poc_email + '">' + json.ocie_poc_name +
                      '</a> ' + 'Phone: (' + json.ocie_poc_phone.substr(0,3) +
                      ') ' + json.ocie_poc_phone.substr(3,3) + '-' + 
                      json.ocie_poc_phone.substr(6,4);
            $("span.POCemail").append(val); 
        }
    );
    $.get(
        "/api/ocie/role_check/",
        function(){
            $("a.logout:contains(Options)").css("display","block");
        }
    );    
}


function getCommonLookups() {
    $.ajax({
        type: 'GET',
        url: '/api/ocie/common_lookups/',
        dataType: "json",
        success: function(json){
            var val = '';
            $.each(json.appointment_types, function(){
	        val += '<span class="legendColorBox ' + this.css_class +
                       '">&nbsp;</span><span class="legendKey">' +
                       this.description + '</span>';
            });
            val += '<p>&nbsp;</p>';
            $("#legendContent").append(val);
            val = '';
            $.each(json.appointment_types, function(){
		val += '<option value="' + this.appointment_type_id + '">' +
                       this.description + '</option>';
	    });
            $("#appointment_type_id").append(val);
            val = '';
            $.each(json.units, function(){
	        val += '<option value="' + this.unit_id + '">' +
		       this.description + '</option>';
	    });
            $("#unit_id").append(val); 
            val = '';
            $.each(json.ranks, function(){
	        val += '<option value="' + this.id + '">' +
                       this.description + '</option>';
            });
            $("select[name='attendee_rank']").append(val);
            setProtoHTML();
            current_date = $.qs('date') ? $.qs('date') : '';
            getDateInfo(current_date);

            $("#button_tasks").click( function(){
                toggleTasks();
                return false;
            });
            $("#button_appointments").click( function(){
                toggleAppointment();
                return false;
            });
            $("#button_search").click( function(){
                toggleSearch();
                return false;
            });
            $("#button_restore").click( function(){
                toggleRestore();
                return false;
            });
        },
        error: function(string){
            if(string.status >= 400 && string.status < 500){
                window.location = "/ocie/";
            }
        }
    });
}


function getDateInfo(value) {
    $("#weeklyScheduleBox").html(proto_html['schedule']);
    var url = '/api/dates/7day/';
    if ( value ){
        url += value + '/';
    }
    amJumping = true;
    $.getJSON(url, function( json ) {
        amJumping = false;
        var val = ' ' + json.days[0].display + ' - ' + json.days[6].display;
        $("#ocieSchedule caption span:first span:first").after(val);
        var day_list = [];
        jQuery.each([6,5,4,3,2,1,0], function(){
	    var val = json.days[this].dow + '<br />' +
		      json.days[this].display;
            $("#ocieSchedule th:nth-child(" + (this + 2) + ")").html(val);
            $("#ocieSchedule colgroup col:nth-child(" + (this + 2) + ")")
	        .attr("id","osDay" + (this + 1) + "Col");
            if( json.today == json.days[this].date ){ 
                $("#ocieSchedule colgroup col:nth-child(" + (this + 2) + ")")
		    .attr("id","osTodayCol");
                $("#ocieSchedule th:nth-child(" + (this + 2) + ")")
		    .addClass("tableCurrentHeadColor");
            }
            day_list[this] = json.days[this].date;
        });
        getEventInfo(day_list, json.days[0].date, json.days[6].date,
		     json.previous, json.next);
    });
}


function getEventInfo( day_list, start, finish, previous, next ) {
    $.ajax({
        type: 'GET',
        url: '/api/ocie/schedule/' + start + '/' + finish + '/',
        dataType: "json",
        async: true,
        success: function(json){
            jQuery.each([0,1,2,3,4,5,6], function() {
                var col = this;
                var day = json[day_list[col]];
                if( day['extended'] ){
	            var val = '<a href="#" class="extHoursMark" ' +
                              'title="Extended Hours Appointments"><img ' +
                              'src="/ocie/images/icons/extHoursMarker.gif">' +
                              '</a>';
                    $("#ocieSchedule th:nth-child(" + (col + 2) + ")")
		        .prepend(val);
                    $("#ocieSchedule th a:last").click( function() {
                        search_term = $.y4m2d2_to_d2m3y4(day_list[col]);
                        $("#protoTasksBox, #protoAppointment").remove();
                        $("#protoSearchResults, #protoRestore").remove();
                        toggleSearch();
                        return false;
                    });
	        }
                var appts = day['appts'];
                if( appts.length ){
                    var simul = day['max_simul'];
                    if( simul <= 8 ){
                        var width = (118 - 8 * (simul) - 2 * (simul-1)) / simul;
                    }else{
                        var width = 1;
                    }
                    appts = setInitialEventPositions(appts);
                    appts = setEventPositions(appts);
                    test = appts;
                    var sel = '#ocieSchedule tbody tr:nth-child(1) ' +
                              'td:nth-child(' + (col + 2) + ')';
                    setEvents(appts, sel, width);                              
                }
            });
        $("#loadingMessage").remove();
	    $("#button_previous").click( function() {
                getDateInfo(previous);
            });
	    $("#button_next").click( function() {
                getDateInfo(next);
            });
        bindPdfButton(start, finish);
        }
    });
}


var bindPdfButton = function(start, finish) {
    $("#button_print").unbind();
    $("#button_print").bind("click", function() {
        postPdfJson(start,finish);
    });
};


function setEvents( appts, sel, width ) {
    jQuery.each(appts, function() {
        var a = '<a href="#"><span ' +
                'schedule_id="' + this['schedule_id'] + '"' +
                'class="appointmentEvent ' + this['css_class'] + '"' +
                'style="height: ' + (23 * this['vert_length'] - 4) + 'px; ' +
                'width: ' + width + 'px; ' +
                'margin-top: ' + (23 * this['vert_pos']) + 'px; ' +
                'margin-left: ' + (width + 10) * this['hor_pos'] + 'px;"' +
                '>' + this['description'] + '</span></a>';    
        $(sel).append(a);
        var schedule_id = this['schedule_id'];
        $(sel + ' a:last').click( function() {
            editAppointment(schedule_id);
            return false;
        });
    });
}


function setInitialEventPositions( appts ) {
    jQuery.each(appts, function() {
        this['hor_pos'] = 0;
    });
    return appts;
}


function setEventPositions( appts ) {
    var conflicts = 0;
    jQuery.each(appts, function() {
        var a = this;
        jQuery.each(appts, function() {
            var b = this;
            if( a != b ){
                if( compareForCollision(a, b) ){
                    b['hor_pos'] += 1;
                    conflicts += 1;
                }
            }
        });
    });    
    if( conflicts ){
        setEventPositions(appts);
    }
    return appts;
}


function compareForCollision( a, b ) {
    if( a['hor_pos'] != b['hor_pos'] ){
        return false;
    }
    if( ( a['vert_pos'] + a['vert_length'] - 1 ) < b['vert_pos'] ){
        return false;
    }
    if( ( b['vert_pos'] + b['vert_length'] - 1 ) < a['vert_pos'] ){
        return false;
    }
    return true;
}


function getTasks() {
    $.getJSON('/api/ocie/schedule/tasks/', function(json) {
        var sel = '#protoTasksBox div.tasksBox div.sidebarContent ' +
                  'span.contentContainer:eq(0)';
        if( json['rescheduled'].length == 0 ){
            $(sel).append('<p>No Appointments to Reschedule.</p>');
        }
        jQuery.each(json['rescheduled'], function() {
	    var appt = '<span class="searchResult"><p><a href="#"><strong>' +
                       this['description'] + '</strong></a></p></span>';
	    $(sel).append(appt);
            var schedule_id = this['schedule_id'];
            $(sel + ' p:last a').click( function() {
                editReschedule(schedule_id);
                return false;
            });
	});
        sel = '#protoTasksBox div.tasksBox div.sidebarContent ' +
              'span.contentContainer:eq(1)';
        if( json['drafted'].length == 0 ){
            $(sel).append('<p>No Drafts.</p>');
        }
        jQuery.each(json['drafted'], function() {
	    var appt = '<span class="searchResult"><p><a href="#"><strong>' +
                       this['description'] + '</strong></a></p></span>';
	    $(sel).append(appt);
            var schedule_id = this['schedule_id'];
            $(sel + ' p:last a').click( function() {
                editDraft(schedule_id);
                return false;
            });
	});
        sel = '#protoTasksBox div.todaysAppointments ' +
              'div.sidebarContent span:eq(0)';
        if( json['today'].length == 0 ){
            $(sel).append('<p>No Appointments Today.</p>');
        }
        jQuery.each(json['today'], function() {
            var appt = '<span class="searchResult"><h5>' + 
                       this['description'] + '</h5><p><a href="#"> ' +
                       '[' + this['schedule_id'] + '] ' +
                       this['appointment_type'] + '<br />' +
                       this['start'] + ' - ' + this['finish'];
	    appt += (
                    ( this['poc_phone'].length == 10 )
                    ? '<br />(' + this['poc_phone'].substr(0,3) + ') ' +
                      this['poc_phone'].substr(3,3) + '-' +
                      this['poc_phone'].substr(6,4)
                    : ''
                    );         
	    appt += (
                    ( jQuery.trim(this['poc_email']) )
                    ? '<br />' + jQuery.trim(this['poc_email'])
                    : ''
                    );
       	    appt += '</a></p></span>';
	    $(sel).append(appt);
            var schedule_id = this['schedule_id'];
            $(sel + ' a:last').click( function() {
                editAppointment(schedule_id);
                return false;
            });
	});
    });
}


function getSearchResults(search_term) {
    search_manager.add({ 
        type: 'GET',
        url: '/api/ocie/schedule/search/?search_term=' + search_term,
        dataType: "json",
        async: true,
        success: function(json) {
            var sel = '#protoSearchResults div.sidebarContent ' +
                      'span.contentContainer';
            $(sel + ' span').remove();
            $.each(json, function() {
                var a = this;
                var appt = '<span class="searchResult"><h5>';
                if(a['attendees'].length > 1){
                    appt += a['unit'] + ' (' + a['attendees'].length + ')';
                }else if(a['attendees'].length == 1){
                    appt += ( (a['attendees'].length == 0 ||
                               a['attendees'][0].last_name == '')
                            ? 'Unknown'
                            : a['attendees'][0].rank_abbreviation + ' ' +
                              a['attendees'][0].last_name );
                }else{
                    appt += a['unit'];
                }
                appt += '</h5><p><a href="#">[' + a['schedule_id'] +
                        '] ' + a['type'] + '<br />' +
                        convertToMilitaryDate(a['start'].substr(0,10)) +
                        ' ' + a['start'].substr(11,2) + 
                        a['start'].substr(14,2) + '-' + 
                        a['finish'].substr(11,2) + 
                        a['finish'].substr(14,2) + '<br />';
                a['poc_phone'] = $.trim(a['poc_phone']);
                appt += ( ((a['poc_phone']).length == 10)
                        ? '(' + a['poc_phone'].substr(0,3) + ') ' +
                          a['poc_phone'].substr(3,3) + '-' +
                          a['poc_phone'].substr(6,4) + '<br />'
                        : '' );
                appt += ( (($.trim(a['poc_email'])).length != 0)
                        ? $.trim(a['poc_email']) + '<br />'
                        : '' );
                var last_names = $.map(a['attendees'], function(att){
                    if($.trim(att.last_name) != ''){
                        return $.trim(att.last_name);
                    }
                });
                appt += last_names.join(', ');
                appt += '</a></p></span>';
                $(sel).append(appt);
                $(sel + ' a:last').click( function(){
                    editAppointment(a['schedule_id']);
                    return false;
                });
            });
        }
    });
}


function getCanceled() {
    $.getJSON('/api/ocie/schedule/canceled/', function(json) {
        var sel = '#protoRestore div.sidebarContent ' +
                  'span.contentContainer';
        if( json.length == 0 ){
            $(sel + ':nth-child(1)').append('<p>No Deleted Appointments.</p>');
        }
        jQuery.each(json, function() {
            var appt = '<span class="searchResult"><h5>' + 
                       this['description'] + '</h5><p><a href="#"> ' +
                       '[' + this['schedule_id'] + '] ' +
                       this['appointment_type'] + '<br />' +
                       this['date'] + ' ' + this['start'] + ' - ' + this['finish'];
	    appt += (
                    ( this['poc_phone'].length == 10 )
                    ? '<br />(' + this['poc_phone'].substr(0,3) + ') ' +
                      this['poc_phone'].substr(3,3) + '-' +
                      this['poc_phone'].substr(6,4)
                    : ''
                    );         
	    appt += (
                    ( jQuery.trim(this['poc_email']) )
                    ? '<br />' + jQuery.trim(this['poc_email'])
                    : ''
                    );
 	    appt += (
                    ( jQuery.trim(this['attendees']) )
                    ? '<br />' + jQuery.trim(this['attendees'])
                    : ''
                    );
       	    appt += '</a></p></span>';
	    $(sel).append(appt);
            var schedule_id = this['schedule_id'];
            $(sel + ' a:last').click( function() {
                editCanceled(schedule_id);
                return false;
            });
	});
    });
}


function deleteAppointment(schedule_id) {
    var url = '/api/ocie/schedule/' + schedule_id + '/';
    $.ajax({
        type: 'DELETE',
        url: url,
        success: function(json){
            getDateInfo();
	    toggleAppointment();
        },
        error: function(){
            console.debug('Error');
        }
    });
}


function toggleTasks() {
    if($("#protoTasksBox").length){
        $("#protoTasksBox").remove();
        $("#button_tasks").removeClass("buttonSelected").addClass("buttonRoll");
        $("div.sidebar").css("z-index","1");
    }else{
        $("#protoTasksBox,#protoAppointment,#protoSearchResults,#protoRestore").remove();
        $("#button_appointments,#button_search,#button_restore").removeClass("buttonSelected").addClass("buttonRoll");
        $("#protoToolbarHTML").after(proto_html['tasks_box']);
        $("#button_tasks").removeClass("buttonRoll").addClass("buttonSelected");
        $("div.sidebar").css("z-index","100");
        getTasks();
    }
}


function toggleAppointment() {
    if($("#protoAppointment").length){
        $("#protoAppointment").remove();
        $("#button_appointments").removeClass("buttonSelected").addClass("buttonRoll");
        $("div.sidebar").css("z-index","1");
    }else{
        $("#protoTasksBox,#protoAppointment,#protoSearchResults,#protoRestore").remove();
        $("#button_tasks,#button_search,#button_restore").removeClass("buttonSelected").addClass("buttonRoll");
        $("#protoToolbarHTML").after(proto_html['appointment']);
        $("#button_appointments").removeClass("buttonRoll").addClass("buttonSelected");
        $("div.sidebar").css("z-index","100");
	setAttendees();
	$("#no_of_attendees").change( setAttendees );
        $("#protoAppointment div.sidebarContent span.contentContainer").append(proto_html['add_appointment_buttons']);
        bindFormButtons();     
    }
}


function toggleSearch() {
    if($("#protoSearchResults").length){
        $("#protoSearchResults").remove();
        $("#button_search").removeClass("buttonSelected").addClass("buttonRoll");
        $("div.sidebar").css("z-index","1");
    }else{
        $("#protoTasksBox,#protoAppointment,#protoSearchResults,#protoRestore").remove();
        $("#button_tasks,#button_appointments,#button_restore").removeClass("buttonSelected").addClass("buttonRoll");
        $("#protoToolbarHTML").after(proto_html['search_results']);
        $("#button_search").removeClass("buttonRoll").addClass("buttonSelected");
        $("div.sidebar").css("z-index","100");
        if( search_term != ''){
            $("#searchTerm").val(search_term);
            getSearchResults(search_term);
        }else{
            $("#searchTerm").focus(function(){
                if( $("#searchTerm").val() == "Start typing to search" ){
                    $("#searchTerm").val('');
                }
            });
        }
        $("#searchTerm").keyup(function() {
            if( $("#searchTerm").val().length > 2 ){
                getSearchResults( $("#searchTerm").val() );
            }
            search_term = $.trim($("#searchTerm").val());
        });
    }
}


function toggleRestore() {
    if($("#protoRestore").length){
        $("#protoRestore").remove();
        $("#button_restore").removeClass("buttonSelected").addClass("buttonRoll");
        $("div.sidebar").css("z-index","1");
    }else{
        $("#protoTasksBox,#protoAppointment,#protoSearchResults,#protoRestore").remove();
        $("#button_tasks,#button_appointments,#button_search").removeClass("buttonSelected").addClass("buttonRoll");
        $("#protoToolbarHTML").after(proto_html['restore']);
        $("#button_restore").removeClass("buttonRoll").addClass("buttonSelected");
        $("div.sidebar").css("z-index","100");
        getCanceled();
    }
}


var editReschedule = function(schedule_id) {
    var buttons = proto_html['edit_reschedule_buttons'];
    return buildForm(schedule_id, buttons);
}


var editDraft = function(schedule_id) {
    var buttons = proto_html['edit_draft_buttons'];
    return buildForm(schedule_id, buttons);
}


var editAppointment = function(schedule_id) {
    var buttons = proto_html['edit_reschedule_buttons'];
    return buildForm(schedule_id, buttons);
}


var editCanceled = function(schedule_id) {
    var buttons = proto_html['restore_draft_buttons'];
    return buildForm(schedule_id, buttons);
}


function buildForm(schedule_id, buttons) {
    $("#protoTasksBox,#protoAppointment,#protoSearchResults,#protoRestore").remove();
    $("#button_tasks,#button_search,#button_restore").removeClass("buttonSelected").addClass("buttonRoll");
    $("#protoToolbarHTML").after(proto_html['appointment']);
    $("#button_appointments").removeClass("buttonRoll").addClass("buttonSelected");
    $("div.sidebar").css("z-index","100");
    $("span.sidebarHead").html('Edit Appointment');
    $("span.input_noShow").attr("style","display:inline;");
    var url = '/api/ocie/schedule/' + schedule_id + '/';
    $.getJSON(url, function(json){
        if( json.walkin ){ $("input#walkin").attr("checked","checked"); }
        if( json.noshow ){ $("input#noshow").attr("checked","checked"); }
        $("#date").val( convertToMilitaryDate(json.start.substr(0,10)) );
        $("#startHour option[value='" + json.start.substr(11,2) + "']").attr("selected","selected");
        $("#endHour option[value='" + json.finish.substr(11,2) + "']").attr("selected","selected");
	if( $("#startMin option[value='" + json.start.substr(14,2) + "']").length == 1 && 
	    $("#endMin option[value='" + json.finish.substr(14,2) + "']").length == 1 )
	{
	    $("#startMin option[value='" + json.start.substr(14,2) + "']").attr("selected","selected");
	    $("#endMin option[value='" + json.finish.substr(14,2) + "']").attr("selected","selected");
	}else{
	    $("#startMin option[value='00']").attr("selected","selected");
	    $("#endMin option[value='00']").attr("selected","selected");	
	}
        $("#appointment_type_id option[value='" + json.appointment_type_id + "']").attr("selected","selected");
        $("#unit_id option[value='" + json.unit_id + "']").attr("selected","selected");
        $("#poc_phone_area").val(json.poc_phone.substr(0,3));
        $("#poc_phone_prefix").val(json.poc_phone.substr(3,3));
        $("#poc_phone_suffix").val(json.poc_phone.substr(6,4));
        $("#poc_email").val(json.poc_email);
        $("#comments").val(json.comments);
        $("#creator").val(json.creator);
        jQuery.map(json.attendees, function(i){
            $("span.attendantTableContainer table.dataEntry").append(proto_html['attendee']);
            $("span.attendantTableContainer table.dataEntry tr:last select[name='attendee_rank'] option[value='" + i.rank + "']").attr("selected","selected");
            $("span.attendantTableContainer table.dataEntry tr:last input[name='attendee_first_name']").val(i.first_name);
            $("span.attendantTableContainer table.dataEntry tr:last input[name='attendee_last_name']").val(i.last_name);
            $("span.attendantTableContainer table.dataEntry tr:last input[name='attendee_ssn']").val(i.ssn);
	});
        $("#no_of_attendees").val(json.attendees.length);
        if( !json.attendees.length ){
            $("#no_of_attendees").val(1);
            $("span.attendantTableContainer table.dataEntry").append(proto_html['attendee']);
        }
        $("#protoAppointment div.sidebarContent span.contentContainer").append(buttons);
        bindFormButtons(schedule_id);
        $("#no_of_attendees").change( setAttendees );        
    });
}


var putAppointment = function() {
    var url = '/api/ocie/schedule/';
    var request_method = 'PUT';
    var pane_toggle = 'Appointments';
    return formSubmit(request_method, url, pane_toggle);
}


var putDraft = function() {
    var url = '/api/ocie/schedule/draft/';
    var request_method = 'PUT';
    var pane_toggle = 'Tasks';
    return formSubmit(request_method, url, pane_toggle);
}


var postAppointment = function(schedule_id) {
    var url = '/api/ocie/schedule/' + schedule_id + '/';
    var request_method = 'POST';
    var pane_toggle = 'Appointments';
    return formSubmit(request_method, url, pane_toggle, schedule_id);
}


var postDraft = function(schedule_id) {
    var url = '/api/ocie/schedule/drafted/' + schedule_id + '/';
    var request_method = 'POST';
    var pane_toggle = 'Tasks';
    return formSubmit(request_method, url, pane_toggle, schedule_id);
}


var postReschedule = function(schedule_id) {
    var url = '/api/ocie/schedule/rescheduled/' + schedule_id + '/';
    var request_method = 'POST';
    var pane_toggle = 'Tasks';
    return formSubmit(request_method, url, pane_toggle, schedule_id);
}


function formSubmit(request_method, url, pane_toggle, schedule_id) {
    $("span#error_general, span#error_server").removeAttr('style');
    $("span#wait_save").attr("style","display:block;");
    item_data = {};
    field_list = ['unit_id','appointment_type_id','poc_email','comments'];
    jQuery.map(field_list, function(i){
	item_data[i] = $("#" + i).val();
    });
    item_data['poc_phone'] = $("#poc_phone_area").val() + $("#poc_phone_prefix").val() + $("#poc_phone_suffix").val();
    item_data['start'] = convertMilitaryDate( $("#date").val() ) + ' ' + $("#startHour").val() + ':' + $("#startMin").val();
    item_data['finish'] = convertMilitaryDate( $("#date").val() ) + ' ' + $("#endHour").val() + ':' + $("#endMin").val();
    item_data['walkin'] = ( $("input#walkin:checked").length ? 1 : 0 );
    item_data['noshow'] = ( $("input#noshow:checked").length ? 1 : 0 );
    var attendee_ranks = new Array();
    var attendee_first_names = new Array();
    var attendee_last_names = new Array();
    var attendee_ssn = new Array();
    $("span.attendantTableContainer table.dataEntry tr:gt(0)").each( function(i) {
        attendee_ranks[i] = $("span.attendantTableContainer table.dataEntry tr:eq(" + (i+1) + ") select[name='attendee_rank'] option:selected").val();
        attendee_first_names[i] = $("span.attendantTableContainer table.dataEntry tr:eq(" + (i+1) + ") input[name='attendee_first_name']").val();
        attendee_last_names[i] = $("span.attendantTableContainer table.dataEntry tr:eq(" + (i+1) + ") input[name='attendee_last_name']").val();
        attendee_ssn[i] = $("span.attendantTableContainer table.dataEntry tr:eq(" + (i+1) + ") input[name='attendee_ssn']").val();

    });
    item_data['attendee_ranks'] = attendee_ranks;
    item_data['attendee_first_names'] = attendee_first_names;
    item_data['attendee_last_names'] = attendee_last_names;
    item_data['attendee_ssn'] = attendee_ssn;
    $.ajax({
        type: request_method,
        url: url,
        data: item_data,
        dataType: "json",
        success: function(json){
            current_date = convertMilitaryDate( $("#date").val() ); 
            getDateInfo(current_date);
            if(pane_toggle == 'Appointments'){
                toggleAppointment();
            }else{
                toggleTasks();
            }
        },
        error: function(){
            $("span#wait_save").removeAttr("style");
            $("span#error_server").attr("style","display:block;");
            bindFormButtons(schedule_id);
        }
    });
}


function bindFormButtons(schedule_id) {
    $("span.contentContainer span a.button").unbind();
    $("#button_save_add").click( function(){
        if( !validateForm() ){
            $("span.contentContainer span a.button").unbind();
            $("span.contentContainer span a.button").click( function(){ return false } );
            putAppointment();
        } 
        return false;
    });
    $("#button_save_draft_add").click( function(){
        $("span.contentContainer span a.button").unbind();
        $("span.contentContainer span a.button").click( function(){ return false } );
        putDraft();
        return false;
    });
    $("#button_save").click( function(){
        if( !validateForm() ){
            $("span.contentContainer span a.button").unbind();
            $("span.contentContainer span a.button").click( function(){ return false } );
            postAppointment(schedule_id);
        } 
        return false;
    });
    $("#button_save_draft").click( function(){
        $("span.contentContainer span a.button").unbind();
        $("span.contentContainer span a.button").click( function(){ return false } );
        postDraft(schedule_id);
        return false;
    });
    $("#button_reschedule").click( function(){
        if( !validateForm() ){
            $("span.contentContainer span a.button").unbind();
            $("span.contentContainer span a.button").click( function(){ return false } );
            postReschedule(schedule_id);
        } 
        return false;
    });
    $("#button_cancel").click( function(){
        toggleAppointment();
        return false;
    });
    $("#button_delete").click( function(){
        $("span.contentContainer span a.button").unbind();
        deleteAppointment(schedule_id);
        return false;
    });    
}


function validateForm() {
    var error_count = 0;
    $("span#error_date, span#error_time").removeClass('highlightError');
    $("span#error_general, span#error_server").removeAttr('style');
    if( !validMilitaryDate( $("#date").val() ) ){
        $("span#error_date").addClass('highlightError');
        error_count += 1;
    }
    if( ( $("#startHour").val() + $("#startMin").val() ) >= ( $("#endHour").val() + $("#endMin").val() ) ){
        $("span#error_time").addClass('highlightError');
        error_count += 1;
    }
    if(error_count){ $("span#error_general").attr("style","display:block;"); }
    return error_count;
}


function setAttendees() {
    if( $("#no_of_attendees").val() < 1 ){ $("#no_of_attendees").val('1'); }
    var desired_attendants = $("#no_of_attendees").val();
    var current_attendants = $("span.attendantTableContainer table.dataEntry tr:gt(0)").length;
    for (var i = current_attendants;i < desired_attendants;i++){
        $("span.attendantTableContainer table.dataEntry").append(proto_html['attendee']);
    }
    $("span.attendantTableContainer table.dataEntry tr:gt(" + desired_attendants + ")").remove();
    $("span.attendantTableContainer table.dataEntry tr").removeClass("altRow");
    $("span.attendantTableContainer table.dataEntry tr:even").addClass("altRow");
}


function setProtoHTML() {
    var proto_pre = {
        'schedule':'protoScheduleHTML',
        'tasks_box':'protoTasksBoxHTML',
        'attendee':'protoAttendeeHTML',
        'appointment':'protoAppointmentHTML',
        'search_results':'protoSearchResultsHTML',
        'restore':'protoRestoreHTML',
        'add_appointment_buttons':'protoAddAppointmentButtonsHTML',
        'edit_appointment_buttons':'protoEditAppointmentButtonsHTML',
        'edit_reschedule_buttons':'protoEditRescheduleButtonsHTML',
        'edit_draft_buttons':'protoEditDraftButtonsHTML',
        'restore_draft_buttons':'protoRestoreDraftButtonsHTML'
    };
    proto_html = {};
    jQuery.each(proto_pre, function(i, val) {
        proto_html[i] = $("#" + val).html();
        $("#" + val).remove();
    });
    search_term = '';
    search_manager = $.manageAjax({
                         manageType: 'abortOld',
                         maxReq: 1,
                         blockSameRequest: true
                     });
}

var postPdfJson = function(start, finish) {
    $.ajax({
        type: 'GET',
        url: '/api/ocie/json/schedule/' + start + '/' + finish + '/',
        dataType:"string",
        async: true,
        success: function(string){
            
            var form = document.createElement('form');
            $(form).attr({
                    action: '/api/pdf/',
                    method: 'post'
                });
            $(form).css('display','none');
            var inp_json = document.createElement('input');
            $(inp_json).attr({
                    type: 'hidden',
                    name: 'pdf',
                    value: string            
                });
            $(form).append(inp_json);
            var inp_template = document.createElement('input');
            $(inp_template).attr({
                    type: 'hidden',
                    name: 'template',
                    value: 'OCIETemplate'            
                });
            $(form).append(inp_template);
            $(document.body).append(form)
            form.submit();
        }        
    });
};

jQuery(function($) {
    $("div.sidebar").css("z-index","1");
    getSiteCfg();
    getCommonLookups();
    setJumpInput();
});


function isAlphaNumKey(code) {
    return 48<=code && code<=90
}

function setJumpInput() {
    $("#jumpday").focus(function (e) {
        $("#jumpday").val('');
    })

    $("#jumpday").keyup(function (e) {
        if (!isAlphaNumKey(e.keyCode)) { return }
        var v = $("#jumpday").val();
        var m = v.match(/^\s*(\d{1,2})\s+([a-zA-Z]{3,3})\s*$/i);
        if (m && !amJumping) {
            var y = new Date().getFullYear()
            var dt = new Date();
            var mo = months2i(m[2]);
            var dy = m[1];
            dt.setMonth(mo);
            dt.setDate(dy);
            if ((typeof mo != 'string') && dt.getMonth()==mo && dt.getDate()==dy) {
                amJumping = true;
                mo+=1;
                mo = (mo < 10 ? "0" : "") + mo;
                dy = (dy.length == 1 ? "0" + dy : dy)
                getDateInfo("" + y + "-" + mo + "-" + dy);
            }
        } 
    })
}
